package example.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.UploadFileRequest;
import example.vo.Link;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

@Log4j
@Service
public class UploadServiceImpl implements UploadService{

    public void uploadstring(String firstKey,String str){
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        InputStream is = new ByteArrayInputStream(str.getBytes());
        ossClient.putObject(Link.bucketName, firstKey, is);
        log.info("Object：" + firstKey + "存入OSS成功。");
        ossClient.shutdown();
        log.info("Completed");
    }

    public void uploadfile(String fileKey){
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        ossClient.putObject(Link.bucketName, fileKey, new File("src/result"));
        log.info("Object：" + fileKey + "存入OSS成功。");
        ossClient.shutdown();
        log.info("Completed");
    }

    public void uploadthread(String fileKey) throws Throwable {
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType("text/plain");     // 指定上传的内容类型。
        UploadFileRequest uploadFileRequest = new UploadFileRequest(Link.bucketName,fileKey);
        uploadFileRequest.setUploadFile("src/result");    // 指定上传的本地文件。
        uploadFileRequest.setTaskNum(5);        // 指定上传并发线程数，默认为1。
        uploadFileRequest.setPartSize(1024 * 1024);   // 指定上传的分片大小。
        uploadFileRequest.setEnableCheckpoint(true);      // 开启断点续传，默认关闭。
        uploadFileRequest.setCheckpointFile("logfileup"); // 记录本地分片上传结果的文件。
        uploadFileRequest.setObjectMetadata(meta);        // 文件的元数据。
        ossClient.uploadFile(uploadFileRequest);          // 断点续传上传。
        ossClient.shutdown();
        log.info("Completed");
    }

}
